package com.kele.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kele.base.common.exception.AppException;
import com.kele.system.mapper.MenuMapper;
import com.kele.system.mapper.UserMapper;
import com.kele.system.model.dto.queryParam.UserListParam;
import com.kele.system.model.entity.Menu;
import com.kele.system.model.entity.User;
import com.kele.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2023/4/23 18:14
 * @Version:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User getUserByUsername(String username) {
        User condition = new User();
        condition.setUsername(username);
        return userMapper.selectOne(condition);
    }

    @Override
    public List<String> getAuthoritiesByUserId(String userId) {
        return userMapper.getAuthoritiesByUserId(userId);
    }

    @Override
    public PageInfo<User> getUserList(UserListParam userListParam) {
        PageHelper.startPage(userListParam.getPage().getPageNum(), userListParam.getPage().getPageSize());
        User user = new User();
        BeanUtils.copyProperties(userListParam, user);
        List<User> userList = userMapper.getUserList(user);
        return new PageInfo<>(userList);
    }

    @Override
    public List<Menu> findMenuByUserId(String userId) {
        List<Menu> menuListById = menuMapper.getMenuListById(userId);
        return menuListById;
    }

    @Override
    public int addUser(User user) {
        User condition = new User();
        condition.setUsername(user.getUsername());
        List<User> select = userMapper.select(condition);
        if (select.size() > 0){
            AppException.cast("用户名已被占用");
        }

        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setUserType("101001");
        user.setStatus("1");

        user.setCreateTime(LocalDateTime.now());
        return userMapper.insertSelective(user);
    }
}
